package com.paic.mario.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.paic.mario.domain.CollectedObject;
import com.paic.mario.domain.ContentObject;
import com.paic.mario.domain.ServiceTempletVo;
import com.paic.mario.service.SystemService;
import com.paic.mario.service.TempletService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
public class MasterController {
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private TempletService templetService;
	
	@RequestMapping(value="/system/getIndexByMaster",method=RequestMethod.GET)
	public  List<Map<String, Object>> getTempletByObjectId(@RequestParam(value="object_id", required=true) int object_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getIndexByServiceId(object_id);
		return reslutList; 
	}
	
	//获取所有主机信息
	@RequestMapping(value="/system/getMasterBySystem",method=RequestMethod.GET)
	public  List<Map<String, Object>> getAllObjectBySystemId(@RequestParam(value="system_id", required=true) int system_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getMasterBySystemId(system_id);
//		for(int t=0 ; t< reslutList.size(); t++){
//			String obj_id = reslutList.get(t).get("obj_id").toString();
//			Map obj_map = new HashMap();
//			obj_map.put("obj_id", obj_id);
//			List<Map<String, Object>> propertiesList = systemService.getPropertiesInfoByObjectId(obj_map);
//			
//			String opr_user = "";
//			String ip = "";
//			for(int o = 0;o <propertiesList.size(); o++){
//				if("opr_user".equals(propertiesList.get(o).get("properties_name"))){
//					opr_user = propertiesList.get(o).get("properties_value").toString();
//				}
//				if("ip".equals(propertiesList.get(o).get("properties_name"))){
//					ip = propertiesList.get(o).get("properties_value").toString();
//				}
//				if("ip".equals(propertiesList.get(o).get("properties_name"))){
//					ip = propertiesList.get(o).get("properties_value").toString();
//				}
//			}
//			obj_map.put("ip", ip);
//			obj_map.put("opr_user", opr_user);
//			((Map)reslutList.get(t)).put("ip", ip);
//			((Map)reslutList.get(t)).put("opr_user", opr_user);
//		}
		//获取服务对应的主机信息和IP
		for(int t=0 ; t< reslutList.size(); t++){
			String host_name = reslutList.get(t).get("host_name").toString();
			Map obj_map = new HashMap();
			obj_map.put("host_name", host_name);
			List<Map<String, Object>> propertiesList = systemService.getHostPropertiesByHostName(obj_map);
			
			
			String hostName = "";
			String ip = "";
			String obj_id = "";
			
			for(int o = 0;o <propertiesList.size(); o++){
				if(propertiesList.get(o) != null){
				if("hostName".equals(propertiesList.get(o).get("property_name"))){
					hostName = propertiesList.get(o).get("property_value").toString();
				}
				if("ip".equals(propertiesList.get(o).get("property_name"))){
					ip = propertiesList.get(o).get("property_value").toString();
				}
				obj_id = propertiesList.get(o).get("obj_id").toString();
				}
			}
			
			obj_map.put("ip", ip);
			obj_map.put("hostName", hostName);
			((Map)reslutList.get(t)).put("ip", ip);
			((Map)reslutList.get(t)).put("obj_id",obj_id);
			((Map)reslutList.get(t)).put("hostName", hostName);
		}
		return reslutList;
	}
	
	@RequestMapping(value="/system/getHostInfoByObjectId",method=RequestMethod.GET)
	public  List<Map<String, Object>> getHostInfoByObjectId(@RequestParam(value="object_id", required=true) int object_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getHostInfoByObjectId(object_id);
		for(int t=0 ; t< reslutList.size(); t++){
			String obj_id = reslutList.get(t).get("obj_id").toString();
			Map obj_map = new HashMap();
			obj_map.put("obj_id", obj_id);
			List<Map<String, Object>> propertiesList = systemService.getPropertiesInfoByObjectId(obj_map);
			
			String opr_user = "";
			String ip = "";
			for(int o = 0;o <propertiesList.size(); o++){
				if("opr_user".equals(propertiesList.get(o).get("property_name"))){
					opr_user = propertiesList.get(o).get("property_value").toString();
				}
				if("ip".equals(propertiesList.get(o).get("property_name"))){
					ip = propertiesList.get(o).get("property_value").toString();
				}
			}
			obj_map.put("ip", ip);
			obj_map.put("opr_user", opr_user);
			((Map)reslutList.get(t)).put("ip", ip);
			((Map)reslutList.get(t)).put("opr_user", opr_user);
			((Map)reslutList.get(t)).put("host_name", reslutList.get(t).get("obj_name").toString());
		}
		return reslutList;
	}
	
	/**
	 * 一键关闭
	 * @param object_id
	 */
	@RequestMapping(value="/system/stopMasterTemplet",method=RequestMethod.GET)
	public int stopMasterTemplet(@RequestParam(value="object_id", required=true) int object_id){
		int cnt =0;
		cnt = systemService.stopMasterTemplet(object_id);
		List<Map<String, Object>> tmpList = systemService.getSelectedTempletByObjectId(object_id);
		String flag ="del";
		//下发
		for(Map<String, Object> tmplet : tmpList){
			String host_name = (String) tmplet.get("host_name");
			String file_name = (String)tmplet.get("indextemplateid");
			String param =(String)tmplet.get("json_text");
			templetService.saveAndload(host_name, file_name, flag, param);
		}
		return cnt;
	}
	
	/**
	 * 一键启动
	 * @param object_id
	 */
	@RequestMapping(value="/system/startMasterTemplet",method=RequestMethod.GET)
	public int startMasterTemplet(@RequestParam(value="object_id", required=true) int object_id){
		int cnt =0;
		List<Map<String,Object>> tmpList = systemService.getUnuseTmp(object_id);
		cnt = systemService.startMasterTemplet(object_id);
		String flag ="add";
		//下发
		for(Map<String, Object> tmplet : tmpList){
			String host_name = (String) tmplet.get("host_name");
			String file_name = (String)tmplet.get("indextemplateid");
			String param =(String)tmplet.get("json_text");
			templetService.saveAndload(host_name, file_name, flag, param);
		}
		return cnt;
	}
	
	/**后台写死
	 * 获取主机可配置模板
	 * @param
	 * @return
	 */
	@RequestMapping(value="/system/getHostTemplet",method=RequestMethod.POST)
	public  List<Map<String, Object>> getHostTemplet(@RequestBody List<Integer> object_ids){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		//暂时写死
		object_ids.clear();
		object_ids.add(101);
		reslutList = systemService.getHostTemplet(object_ids);
		return reslutList; 
	}
	
	/**
	 * 获取主机信息通过主机名
	 * @param
	 * @return
	 */
	@RequestMapping(value="/system/getHostInfoByHostName",method=RequestMethod.GET)
	public  List<Map<String, Object>> getHostInfoByHostName(@RequestParam(value="host_name", required=true) String host_name,@RequestParam(value="system_id", required=true) String system_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		
		Map map = new HashMap();
		map.put("host_name", host_name);
		map.put("system_id", system_id);
		
		reslutList = systemService.getHostInfoByHostName(map);
		//获取服务对应的主机信息和IP
		for(int t=0 ; t< reslutList.size(); t++){
			Map obj_map = new HashMap();
			obj_map.put("host_name", reslutList.get(t).get("obj_name").toString());
			List<Map<String, Object>> propertiesList = systemService.getHostPropertiesByHostName(obj_map);
			
			String hostName = "";
			String ip = "";
			String obj_id = "";
			if(propertiesList.get(0) != null){
			 for(int o = 0;o <propertiesList.size(); o++){
				if("hostName".equals(propertiesList.get(o).get("property_name"))){
					hostName = propertiesList.get(o).get("property_value").toString();
				}
				if("ip".equals(propertiesList.get(o).get("property_name"))){
					ip = propertiesList.get(o).get("property_value").toString();
				}
				obj_id = propertiesList.get(o).get("obj_id").toString();
			  }
			}
			((Map)reslutList.get(t)).put("ip", ip);
			((Map)reslutList.get(t)).put("obj_id",obj_id);
			((Map)reslutList.get(t)).put("host_name", reslutList.get(t).get("obj_name").toString());
		}
		return reslutList; 
	}
	
	@RequestMapping(value="/system/addObject",method=RequestMethod.POST) 
	public  int addObject(@RequestBody CollectedObject cobj){ 
		int cnt = 0;
		cnt += systemService.addObject(cobj);
		int obj_id = cobj.getObj_id();
		List<Map<String,Object>> propertiesList = cobj.getProperties();
		cnt += systemService.addObjectProperties(propertiesList);
		return cnt;
	}
	
	@RequestMapping(value="/system/updateObject",method=RequestMethod.PUT) 
	public  int updateObject(@RequestBody CollectedObject cobj){ 
		int cnt = 0;
		cnt += systemService.updateObject(cobj);
		return cnt;
	}
	
	@RequestMapping(value="/system/delObject",method=RequestMethod.DELETE) 
	public  int delObject(@RequestParam(value="object_id", required=true) int object_id){ 
		int cnt = 0;
		cnt += systemService.delObject(object_id);
		return cnt;
	}
	
	/**
	 * 根据type_id获取主机、应用等属性
	 */
	@RequestMapping(value="/system/getObjProperties",method=RequestMethod.GET) 	
	public  List<Map<String,Object>> getObjProperties(@RequestParam(value="type_id", required=true) int type_id){ 
		 List<Map<String,Object>> list = new  ArrayList<Map<String,Object>>();
		 systemService.getObjProperties(type_id);
		 return list;
	}
	

	
	
	/**
	 * 获取模板属性
	 * @param templet_id
	 * @return
	 */
	@RequestMapping(value="/system/getTempNewProperties",method=RequestMethod.GET)
	public Map<String,Object> getTempNewProperties(@RequestParam(value="templet_id", required=true) int templet_id){ 
	String content = systemService.getTempContent(templet_id);
	Map<String,Object> map = new Gson().fromJson(content, new TypeToken<Map<String,Object>>() {}.getType());
	return map;
	}
	
	/**
	 * 获取已配置模板属性值
	 * @param templet_id
	 * @return
	 */
	@RequestMapping(value="/system/getTempNewPropertiesValue",method=RequestMethod.GET)
	public  Map<String,Object> getTempNewPropertiesValue(@RequestParam(value="id", required=true) int id){ 
		String content = systemService.getTempJsonText(id);
		Map<String,Object> map = new Gson().fromJson(content, new TypeToken<Map<String,Object>>() {}.getType());
		return map;
	}
	
	/**
	 * add下发接口
	 * @param service_list
	 * @return
	 */
	@RequestMapping(value="/system/addNewServiceTemplet",method=RequestMethod.POST)
	public  int addNewServiceTemplet(@RequestBody List<Map> service_list ){ 
		int cnt =0;
		 int templet_id = (int)service_list.get(0).get("templet_id");
		 for(Map map : service_list){
			 Map<String,Object> jsonMap = (Map<String,Object>) map.get("templet_properties");
        	
        	 //落库
        	 //只能一个一个服务一个服务的入库
        	 ServiceTempletVo insert_Vo =new ServiceTempletVo();
        	 insert_Vo.setObj_id(map.get("obj_id").toString());
        	 insert_Vo.setTemplet_id(map.get("templet_id").toString());
        	 String host_name = map.get("host_name").toString();
        	 insert_Vo.setHost_name(host_name);
        	 //转成String格式
        	 JSONObject json=JSONObject.fromObject(jsonMap);
        	 insert_Vo.setJson_text(json.toString());
        	 Map insert_map = systemService.addOneServiceTemplet(insert_Vo);	 
        	 cnt += Integer.parseInt(insert_map.get("cnt").toString());
      	     String down_id = insert_map.get("id").toString();
        	 
        	 //根据上面落库，生成下发的信息,必须有的三个参数,filename,indextemplateid,host_name
        	 String file_name= map.get("service_id").toString() + templet_id + down_id;
        
        	 map.put("indextemplateid", map.get("service_id").toString() + templet_id + down_id);
        	 map.put("id", down_id);
        	
        	 
        	 //回写加入indextemplateid
        	 Map<String,Object> infoMap= (Map<String,Object>)jsonMap.get("info");
        	 infoMap.put("indextemplateid", map.get("service_id").toString() + templet_id + down_id);
        	 map.put("templet_properties", JSONObject.fromObject(jsonMap).toString());
        	 
        	 //回写这个文件名to配置表库中
        	 int update_indextemplateid_count = systemService.updateOneServiceIndextemplateid(map);
        	 //转换成下发格式的map
        	Map<String,Object>  downMap=  diguiMap(jsonMap,4);
        	 JSONObject downjson=JSONObject.fromObject(jsonMap);
//             map.put("content",Properties);   //下发需要的content
        	String flag ="add";
        	//调用agent的下发接口
			JSONObject json_returnStr = templetService.saveAndload(host_name, file_name, flag, downjson.toString());
         }
         
		return cnt;
	}
	
	public Map<String,Object>  diguiMap(Map<String,Object> jsonMap,int num){
		if(num==1){
			 Set<Entry<String, Object>> entries = jsonMap.entrySet();
			 for (Entry<String, Object> entry : entries) {
				 jsonMap.put(entry.getKey(), entry.getValue());
			 }
			 return jsonMap;
		}else{
			 Set<Entry<String, Object>> entries = jsonMap.entrySet();
			 for (Entry<String, Object> entry : entries) { 
		 			//三种情况  1.数组  2.Map 3.其他基础类型值
				    if(entry.getValue() instanceof List){
				    	List list = (List) entry.getValue();
				    	//判断数组是否为 模板类型，模板类型取值
				    	if("Y".equals(list.get(3))||"N".equals(list.get(3))){
		 				jsonMap.put(entry.getKey(),list.get(2));
				    	}else{
				    	jsonMap.put(entry.getKey(), entry.getValue());
				    	}
		 			}else if(entry.getValue() instanceof Map){
		 				Map<String,Object> map= (Map<String,Object>) entry.getValue();
		 				jsonMap.put(entry.getKey(),diguiMap(map,num-1));
		 			}else{
		 			  jsonMap.put(entry.getKey(), entry.getValue());
		 			}
		 		} 
			 return jsonMap;
		}
	}
	
	
	/**
	 * update下发接口
	 * @param id
	 * @param object_id
	 * @param json_text
	 * @return
	 */
	@RequestMapping(value="/system/updateNewServiceTemplet",method=RequestMethod.POST)
	public  int updateNewServiceTemplet(@RequestBody Map map){
		 int cnt =0;
		 String id = map.get("id").toString();
		 String object_id = map.get("object_id").toString();
		 Map<String,Object> jsonMap = (Map<String,Object>) map.get("json_text");
		 JSONObject json=JSONObject.fromObject(jsonMap);
    	 Map<String,Object> upmap =  (Map<String, Object>) map.get("update_data");
    	 Set<Entry<String, Object>> entries = upmap.entrySet();
 		 for (Entry<String, Object> entry : entries) { 
 			map.put(entry.getKey(), entry.getValue());
 		 }
    	 String host_name = (String) map.get("host_name");
		 String file_name = (String) map.get("indextemplateid");
		 map.put("file_name",file_name);
    	
		 //转换成下发格式的map
     	 Map<String,Object>  downMap=  diguiMap(jsonMap,4);
     	 JSONObject downjson=JSONObject.fromObject(jsonMap);

		 cnt = templetService.callbackTotempletConfig(id, object_id ,json.toString());
		 JSONObject json_returnStr = templetService.saveAndload(host_name, file_name, "update", downjson.toString());
		 return cnt;
	}

}
